//
//  ViewController.m
//  HttpRequestDemo
//
//  Created by joker on 15/6/19.
//  Copyright (c) 2015年 joker. All rights reserved.
//

#import "ViewController.h"

#import "ASIFormDataRequest.h"
#import "ASIHTTPRequest.h"
#import "ASIHTTPRequestConfig.h"
#import <CommonCrypto/CommonDigest.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
    //md5 采用UTF16位编码格式编码，注意滤除NSString转cStr时尾部的'\0'
- (NSString *)getMd5_32Bit_String:(NSString *)srcString{
    const char *cStr = [srcString cStringUsingEncoding:NSUTF16StringEncoding];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, [srcString length]*2, result );
    return [NSString
            stringWithFormat: @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1],result[2], result[3],result[4], result[5],result[6], result[7],
            result[8], result[9],result[10], result[11],result[12], result[13],result[14], result[15]
            ];
}

- (IBAction)logIn:(UIButton *)sender {
        //https://service.oa.jiuan-roa.com/
    //服务器地址https://oa.jiuan.com:4433/
        NSURL *serverSite=[NSURL URLWithString:  @"https://oa.jiuan.com:4433/"];
//        NSURL *serverSite=[NSURL URLWithString:  @"https://192.168.1.24/"];
    //API URL路径
//    MobileOfficeAutomationAPI/GGBMessageListWeb.ashx
//    MobileOfficeAutomationAPI/LoginWeb.ashx
//    NSURL *queryURL=[NSURL URLWithString:@"MobileOfficeAutomationAPI/GGBMessageListWeb.ashx" relativeToURL:serverSite];
    
    NSURL *queryURL=[NSURL URLWithString:@"MobileOfficeAutomationAPI/LoginWeb.ashx" relativeToURL:serverSite];

    NSLog(@"%@",[queryURL absoluteString]);
    
    //获取控件中的用户名和密码信息
    NSString *userName=self.userName.text;
    NSString *userPassword=self.userPassword.text;
    
    NSString *md5UserPasswords=[self getMd5_32Bit_String:userPassword];
    NSLog(@"md5 password: %@", md5UserPasswords);
    
//    NSString *tmpString=[md5UserPasswords uppercaseString];
    
    /*MD5 Coding phase to be added*/
    
    NSDictionary *userInfo=@{@"LogonName": userName,@"PassWord":md5UserPasswords };
    
//    NSDictionary *testInfo=@{@"OAfUserID":@"ba5dbfa8-0b13-49cd-a069-689b71ed47c5",@"AccessKey":@"39d931ef-ec99-41c0-8b5a-c4ec6a015200"};
    
    NSLog(@"userInfo=%@", userInfo);

    NSData *contentData=[NSJSONSerialization dataWithJSONObject:userInfo options:kNilOptions error:nil];
    
//    NSData *contentData=[NSJSONSerialization dataWithJSONObject:testInfo options:kNilOptions error:nil];
    
    NSString *contentString=[[NSString alloc] initWithData:contentData encoding:NSUTF8StringEncoding];
    NSLog(@"contentString=\n%@",contentString);
        //按协议规定，将发送内容与Content组成键值对
    
    
#pragma mark -there are two methods be used to communication
    
    BOOL isUseThirdFramwork=false;

    /*通过是否注释下面一行来选择是使用第三方请求库还是SDK方式进行服务器请求*/
          isUseThirdFramwork=true;
    
    if(!isUseThirdFramwork){
        [self useMyOwnMethod:queryURL postContentJSONString:contentString];
    }
    else{
        [self useThirdpartFramework:queryURL postContentJSONString:contentString];
        
    }
}

-(void)useMyOwnMethod:(NSURL *)queryURL postContentJSONString:(NSString *)contentString{
    
            NSString *jsonString=[NSString stringWithFormat:@"content=%@",contentString];
            NSLog(@"sendMessageJsonString=\n%@",jsonString);
            NSData *jsonData=[jsonString dataUsingEncoding:NSUTF8StringEncoding];
        
            //设置http请求
            NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:queryURL];
            [request setHTTPMethod:@"POST"]; //设置请求方式为POST
            [request setHTTPBody:jsonData]; //设置发送的数据
        
            NSURLResponse *urlRespond;//用于接收POST请求的返回数据
            NSError *error; //用于记录服务器的返回错误信息
        
                //连接服务器，并返回请求数据
            NSData *respond=[NSURLConnection sendSynchronousRequest:request returningResponse:&urlRespond error:&error];
    
            if(!error){
                NSDictionary *responseDict=[NSJSONSerialization JSONObjectWithData:respond options:NSJSONReadingMutableLeaves error:&error];
    
                NSLog(@"The response is :\n%@", [[NSString alloc] initWithData:respond encoding:NSUTF8StringEncoding]);
                NSString *displayString;
                NSString *displayTitle;
    
   
                switch ([responseDict[@"Result"] integerValue]) {
                    case 1:
                        displayTitle=@"登录成功";
                        displayString=@"用户登录成功";
                        NSLog(@"%@",responseDict);
                        /*解析返回的数据*/
                        break;
                    default:
                        displayTitle=@"请求错误";
                        displayString=[NSString stringWithFormat:@"错误代码:%@\n错误信息:%@",responseDict[@"ResultMessage"],responseDict[@"ReturnValue"]];
                        break;
                }
                [self showLogResultTitle:displayTitle withMessage:displayString];
            }
            else
            {
                [self showLogResultTitle:@"POST请求返回错误信息" withMessage:[error description]];
            }
}

-(void)useThirdpartFramework:(NSURL*) queryURL postContentJSONString:(NSString *)contentString{
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:queryURL];
    [request setAuthenticationScheme:@"https"];
    [request setValidatesSecureCertificate:NO];

    [request setPostValue:contentString forKey:@"content"];
    [request startSynchronous];
  
    NSError *error = [request error];
    NSString *response;
    
    if(!error)
    {
        response = [request responseString];
        NSLog(@"%@",response);
        
        NSData * responseData=[response dataUsingEncoding:NSUTF8StringEncoding];
        NSError *error;
       
        NSDictionary *responseDict=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];
        
        NSString *displayString;
        NSString *displayTitle;
        
        if(!error){
            switch ([responseDict[@"Result"] integerValue]) {
                case 1:
                    displayTitle=@"登录成功";
                    displayString=@"用户登录成功";
                    /*解析返回的数据*/
                    break;
                default:
                    displayTitle=@"请求错误";
                    displayString=[NSString stringWithFormat:@"错误代码:%@\n错误信息:%@",responseDict[@"ResultMessage"],responseDict[@"ReturnValue"]];
                    break;
            }
        }
        [self showLogResultTitle:displayTitle withMessage:displayString];
    }
    else
    {
        [self showLogResultTitle:@"POST请求返回错误信息" withMessage:[error description]];
    }
 }
    //用于弹出对话框显示临时信息
-(void) showLogResultTitle:(NSString *) showTitle  withMessage:(NSString *)willShowMessage {
    
    UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:showTitle message:willShowMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    
    [alertView show];
}
@end
